/**
 * 无限滚动背景  
 * 支持横向和纵向
 */
const {ccclass, property} = cc._decorator;

//滚动方向   
enum ROLL_DIRECTIION {
    HORIZONTAL,
    VERTICAL
}

@ccclass
export default class ScrollCamera extends cc.Component {
    
    @property(cc.Integer)
    speed:number = 300; 
    @property([cc.Node])
    loopGrounds:cc.Node[] = [];

    @property({
        type:cc.Enum(ROLL_DIRECTIION)
    })  
    DIR:ROLL_DIRECTIION = ROLL_DIRECTIION.HORIZONTAL;
    
    camera:cc.Camera;

    @property isStop:boolean = false;
  
    start () {
        this.camera = this.getComponent(cc.Camera);
        //初始化背景图片位置
        let node:cc.Node = this.loopGrounds[0] as cc.Node;

        if(this.DIR == ROLL_DIRECTIION.HORIZONTAL){
            let startX = -(cc.winSize.width - node.width)/2;
            node.position = cc.v3(startX, 0);
            for (let i = 1; i < this.loopGrounds.length; i++) {
                let front = this.loopGrounds[i - 1];
                node = this.loopGrounds[i];
                node.position = cc.v3(front.x + (front.width + node.width) / 2,0 );   
            } 
        }else{
            let startY = -(cc.winSize.height - node.height)/2
            node.position = cc.v3(0, startY);
            for (let i = 1; i < this.loopGrounds.length; i++) {
                let front = this.loopGrounds[i - 1];
                node = this.loopGrounds[i];
                node.position = cc.v3(0, front.y + (front.height + node.height) / 2);   
            } 
        } 
    }
 
    update(dt) { 
        if(this.isStop) return;
        let current = this.loopGrounds[0];
        if(this.DIR == ROLL_DIRECTIION.HORIZONTAL){
            let offset = (cc.winSize.width - current.width) / 2;     
            if (this.camera.node.x > current.x + current.width + offset) { 
                let last = this.loopGrounds[this.loopGrounds.length - 1];
                this.loopGrounds.shift();
                this.loopGrounds.push(current);
                current.x = last.x + (last.width + current.width) / 2; 
            }
            this.node.x += dt * this.speed; 
        }else{ 
            let offset = (cc.winSize.height - current.height) / 2;     
            if (this.camera.node.y > current.y + current.height + offset) { 
                let last = this.loopGrounds[this.loopGrounds.length - 1];
                this.loopGrounds.shift();
                this.loopGrounds.push(current);
                current.y = last.y + (last.height + current.height) / 2; 
            }
            this.node.y += dt * this.speed; 
        }
    } 
}
